//
//  MainObjectWay.m
//  Shopping
//
//  Created by 刘萍 on 2017年11月23日 星期四.
//  Copyright © 2017年 MR_李先生. All rights reserved.
//

#import "MainObjectWay.h"
#import <CommonCrypto/CommonDigest.h>


@implementation MainObjectWay


/** 加载界面 */
+ (MBProgressHUD *)CreateHUDView:(UIView *)View{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:View animated:YES];
    hud.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    return hud;
}

/** 请求结果  */
+ (BOOL)IsSucceedWithCode:(id)code{
    NSString * CodeStr = [NSString stringWithFormat:@"%@",code];
    return [CodeStr isEqualToString:@"200"];
}

/** 手机号是否正确 */
+ (BOOL)IsMobileWithString:(NSString *)MobileStr{
    if (MobileStr.length != 11)
    {
        return NO;
    }
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,145,155,156,170,171,175,176,185,186
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,149,153,170,173,177,180,181,189
     */
    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:MobileStr] == YES)
        || ([regextestcm evaluateWithObject:MobileStr] == YES)
        || ([regextestct evaluateWithObject:MobileStr] == YES)
        || ([regextestcu evaluateWithObject:MobileStr] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


/**
 验证身份证号码是否正确
 
 @param IDNumber 需要验证的身份证号码
 @return 返回值 YES或NO表示该身份证号码是否符合国家标准
 */
+ (BOOL)isCorrect:(NSString *)IDNumber {
    NSMutableArray *IDArray = [NSMutableArray array];
    // 遍历身份证字符串,存入数组中
    for (int i = 0; i <18; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [IDNumber substringWithRange:range];
        [IDArray addObject:subString];
    }
    // 系数数组
    NSArray *coefficientArray = @[@7, @9, @10, @5, @8, @4, @2, @1, @6, @3, @7, @9, @10, @5, @8, @4, @"2"];
    // 余数数组
    NSArray *remainderArray = @[@"1", @"0", @"X", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    // 每一位身份证号码和对应系数相乘之后相加所得的和
    int sum = 0;
    for (int i = 0; i <17; i++) {
        int coefficient = [coefficientArray[i] intValue];
        int ID = [IDArray[i] intValue];
        sum += coefficient * ID;
    }
    // 这个和除以11的余数对应的数
    NSString *str = remainderArray[(sum % 11)];
    // 身份证号码最后一位
    NSString *string = [IDNumber substringFromIndex:17];
    // 如果这个数字和身份证最后一位相同,则符合国家标准,返回YES
    return [str isEqualToString:string];
}


+ (void)PostWithMethod:(NSString *)MethodString andAction:(NSString *)ActionString andAddParam:(BOOL)AddParam parameters:(NSMutableDictionary *)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    
    NSString * UrlStr = [NSString stringWithFormat:@"http://%@",HeadURL];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:MethodString forKey:@"method"];
    [dic setObject:ActionString forKey:@"action"];
    if (AddParam) {
        [dic setObject:parameters forKey:@"param"];
    }
    
    NSMutableDictionary * dic01 = [[NSMutableDictionary alloc] init];
    [dic01 setObject:dic forKey:@"data"];
    
    NSLog(@"请求的接口 = %@",UrlStr);
    NSLog(@"请求上传的参数%@",dic01);
    
    [manager POST:UrlStr parameters:dic01 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            
            failure(error);
        }
    }];
    
}
+ (void)PostWithMethod:(NSString *)MethodString andAction:(NSString *)ActionString andAddParam:(BOOL)AddParam parameters:(NSMutableDictionary *)parameters Name:(NSString *)Name formData:(NSArray *)ImageArray success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    
    NSString * UrlStr = [NSString stringWithFormat:@"http://%@",HeadURL];
    AFHTTPSessionManager * manage = [AFHTTPSessionManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:MethodString forKey:@"method"];
    [dic setObject:ActionString forKey:@"action"];
    
    if (AddParam) {
        [dic setObject:parameters forKey:@"param"];
    }
    
    NSMutableDictionary * dic01 = [[NSMutableDictionary alloc] init];
    [dic01 setObject:dic forKey:@"data"];
    NSLog(@"请求的接口 = %@",UrlStr);
    NSLog(@"请求上传的参数%@",dic01);
    [manage POST:UrlStr parameters:dic01 constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
         for (int i = 0; i < ImageArray.count; i ++) {
             UIImage * iam = ImageArray[i];
             NSData * D = UIImagePNGRepresentation(iam);
             NSLog(@"未压缩%luKB ",(unsigned long)D.length/1024);
             
             NSData * imageData = [self compressImage:ImageArray[i] WithMaxLength:100*1024];
             NSLog(@"压缩后%luKB ",(unsigned long)imageData.length/1024);
             //获取时间戳  设置图片名称
             NSDate *date = [NSDate date];
             NSDateFormatter *formormat = [[NSDateFormatter alloc]init];
             [formormat setDateFormat:@"yyyyMMddHHmmssSSS"];
             NSString *dateString = [formormat stringFromDate:date];
             NSString *ImageName = [NSString  stringWithFormat:@"%@.jpg",dateString];
            
             [formData appendPartWithFileData:imageData name:Name fileName:ImageName mimeType:@"image/jpg/png/jpeg"];
         }
     } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         if (success) {
             success(responseObject);
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         if (failure) {
             failure(error);
         }
     }];
}

+ (NSData *)compressImage:(UIImage *)image WithMaxLength:(NSUInteger)maxLength{
    // Compress by quality
    NSData * imageJPGData = UIImageJPEGRepresentation(image, 1);
    NSLog(@"JPG 大小 = %ldB",imageJPGData.length);
    
    NSData *imagePNGData = UIImagePNGRepresentation(image);
    NSLog(@"PNG 大小 = %ldB",imagePNGData.length);
    
    //进行图像尺寸的压缩
    CGSize imageSize = image.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    NSLog(@"图片原长 %f 宽 %f",width,height);
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>600||height>600) {
        if (width>height) {
            CGFloat scale = height/width;
            width = 600;
            height = width*scale;
        }else{
            CGFloat scale = width/height;
            height = 600;
            width = height*scale;
        }
        //2.宽大于1280高小于1280
    }else if(width>600||height<600){
        CGFloat scale = height/width;
        width = 600;
        height = width*scale;
        //3.宽小于1280高大于1280
    }else if(width<600||height>600){
        CGFloat scale = width/height;
        height = 600;
        width = height*scale;
        //4.宽高都小于1280
    }else{
    }
    
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [image drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSLog(@"缩小后图片长 %f 宽 %f",newImage.size.width,newImage.size.height);
    
    NSData *NewImageData = UIImagePNGRepresentation(newImage);
    NSLog(@"缩小后%ldB",NewImageData.length);
    
    
    if (NewImageData.length < maxLength) {
        return NewImageData;
    }else{
        CGFloat compression = 1;
        CGFloat max = 1;
        CGFloat min = 0;
        for (int i = 0 ; i < 6; i ++) {
            compression = (max + min)/2;
            NSLog(@"suofangbi = %f",compression);
            NSLog(@"suofang = %f",NewImageData.length * compression);
            if (NewImageData.length * compression < maxLength * 0.9) {
                min = compression;
            }else if (NewImageData.length * compression > maxLength){
                max = compression;
            }else{
                break;
            }
        }
        NSData *data = UIImageJPEGRepresentation(newImage, compression);
        NSLog(@"最后图片大小%ldB",data.length);
        return data;
    }
}


+ (CGFloat)FileSize{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :cachePath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :cachePath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :fileName];
        NSFileManager * manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath :fileAbsolutePath]){
            folderSize += [[manager attributesOfItemAtPath :fileAbsolutePath error : nil] fileSize];
        }else{
            folderSize += 0;
        }
    }
    
    return folderSize/( 1024.0 * 1024.0);
    
}

+ (void)RemoveFileSize{
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
    //NSLog ( @"cachpath = %@" , cachePath);
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
        
        if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
            [[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
        }
    }
}




/**
 MD5加密

 @param oldString 需要加密的字符串
 @return 加密后的字符串
 */
+(NSString *)MD5WithString:(NSString *)oldString{
    const char *cStr = [oldString UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}

//+(void)ToBuyShopWithWXPay:(NSMutableDictionary *)dic{
//    //需要创建这个支付对象
//    PayReq *req   = [[PayReq alloc] init];
//    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
//    req.openID = dic[@"appid"];
//    // 商家id，在注册的时候给的
//    req.partnerId = dic[@"partnerid"];
//    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
//    req.prepayId  = dic[@"prepayid"];
//    // 根据财付通文档填写的数据和签名
//    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
//    req.package   = dic[@"package"];
//    // 随机编码，为了防止重复的，在后台生成
//    req.nonceStr  = dic[@"noncestr"];
//    // 这个是时间戳，也是在后台生成的，为了验证支付的
//    NSString * stamp = dic[@"timestamp"];
//    req.timeStamp = stamp.intValue;
//    // 这个签名也是后台做的
//    req.sign = dic[@"sign"];
//    //发送请求到微信，等待微信返回onResp
//    [WXApi sendReq:req];
//
//
//    NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dic objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
//
//}



+(UIImage *)ChangeImageSize:(UIImage *)image toKb:(NSInteger)kb{
    
    if (!image) {
        return image;
    }
    if (kb<1) {
        return image;
    }
    
    kb*=1024;
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"当前大小:%fkb",(float)[imageData length]/1024.0f);
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
    
}

+ (UIViewController*)currentViewController {
    
    // Find best view controller
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self findBestViewController:viewController];
    
}


+ (UIViewController*)findBestViewController:(UIViewController*)vc {
    
    if ([vc isKindOfClass:[MainController01 class]]) {
        return vc;
    }else if (vc.presentedViewController) {
        
        // Return presented view controller
        return [self findBestViewController:vc.presentedViewController];
        
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        
        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
        
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        
        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.topViewController];
        else
            return vc;
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        
        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.selectedViewController];
        else
            return vc;
        
    } else {
        
        // Unknown view controller type, return last child view controller
        return vc;
        
    }

}




/**
 富文本 添加特殊的字体颜色

 @param str 整体字符串
 @param oneStr 需要设置颜色的字符串
 @param colorOne 字体颜色
 @return 设置后的富文本 字符串
 */
+ (NSMutableAttributedString *) setString:(NSString *)str withColorStr:(NSString *)oneStr andColor:(UIColor *)colorOne{
    NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange range1 = [[hintString string] rangeOfString:oneStr];
    [hintString addAttribute:NSForegroundColorAttributeName value:colorOne range:range1];
    return hintString;
}



+ (void)IsAuth:(UIViewController *)Controller{
    
    UIAlertController* Authalert = [UIAlertController alertControllerWithTitle:@"提示" message:@"照片或相机被禁用，请在设置-隐私中开启" preferredStyle:UIAlertControllerStyleAlert];
    
    [Authalert addAction:[UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        
        NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];
        
        if ( [[UIApplication sharedApplication] canOpenURL: url] ) {
            
            NSURL*url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }]];
    
    [Authalert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
    }]];
    
    [Controller presentViewController:Authalert animated:YES completion:nil];
    
}



/**
 登入提示
 
 @param Controller 需要加载的界面
 */
+ (void)IsLoginApp:(UIViewController *)Controller{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你暂时未登入账号" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"登入" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
        
        //        LoginAppController * login = [[LoginAppController alloc] init];
        //
        //        [Controller.navigationController pushViewController:login animated:YES];
        
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
        
    }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [Controller presentViewController:alert animated:YES completion:nil];
}



@end
